package com.aisino.inveli.vinda.service.impl;

import com.aisino.inveli.vinda.entity.Customer;
import com.aisino.inveli.vinda.repository.CustomerRepository;
import com.aisino.inveli.vinda.service.CustomerService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

/**
 * @author leifeng
 * @Date 2017-11-17
 **/
@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerRepository customerRepository;

    @Transactional
    @Override
    public Boolean saveAll(List<Customer> customerList) {
        Boolean flag = true;
        for (int i = 0; i < customerList.size(); i++) {
            Customer customer = customerList.get(i);
            customer.setId(i+1);
            Customer save = customerRepository.save(customer);
            if (save.getId()==null){
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public Customer queryCusByName(String[] header) {
        List<Customer> cusList = customerRepository.findAllByCusName(header[1]);
        Customer customer = new Customer();
        if (cusList.size() == 0){
            customer.setCusName(header[1]);
            customer.setRegNumber(header[2]);
            customer.setAddAndTel(header[3]);
            customer.setBank(header[4]);
        }else {
            customer = cusList.get(cusList.size()-1);
        }
        return customer;
    }

    @Override
    public List<Customer> queryCusListByName(String name) {
        return customerRepository.findAllByCusName(name);
    }

    @Override
    public void updateCustomerSelect(Customer customer) {
        customerRepository.updateCustomer();
        customer.setIsSelected(true);
        customerRepository.save(customer);
    }

    @Override
    public Customer queryCusBySelected() {
        return customerRepository.queryByIsSelected(true);
    }

    @Override
    public Page<Customer> findAllCustomer(Integer param, String keywordText) {
        PageRequest pageRequest = new PageRequest(param, 20, null);
        if ("".equals(keywordText)){
            return customerRepository.findAll(pageRequest);
        }else {
            keywordText = "%"+keywordText+"%";
            return customerRepository.findByCusNameLike(keywordText,pageRequest);
        }
    }

    @Override
    public void delCustomerById(Integer id) {
        customerRepository.delete(id);
    }

    @Override
    public void save(Customer customer) {
        customerRepository.save(customer);
    }

}
